app.controller("billingRuleCtrl", function ($scope,$interval, $http, billingRuleService) {

    //----------分页参数------------
    $scope.pageRowSize = 10;
    $scope.curPage = 1;

    //-----------------------------

    $scope.object = {};
    $scope.formMode = false;
    $scope.errors = {};

    $scope.isSuperAdmin = false;

    //--------------初始化菜单---------------
    $scope.initMenu = function () {
        showSecondMenu('billingManage');
        selectSecondMenu('billingRuleManage');
    }
    $scope.initMenu();

    //---------------错误信息--------------
    $scope.requestError = function () {
        $scope.errorMessage = "unknown error!"
    };

    $scope.init = function () {
        //默认加载计费规则Tree结构
        $scope.getTreeForBillingRule();

        var span_superAdmin = $("#span_superAdmin").text();
        if(span_superAdmin == "true"){
            $scope.isSuperAdmin = true;
        }
    };

    //编辑计费规则
    $scope.editBillingRule = function () {
        //非空判断
        if (NullOrUndefined($scope.billingRuleObject.ruleAbbrev)) {
            promptMsg("请输入规则简称！");
            return false;
        }

        if (NullOrUndefined($scope.billingRuleObject.ruleRate)) {
            promptMsg("请输入重发率！");
            return false;
        }

        //获取表中的计费阶梯，放入数组中传入后台
        var billingLaddersArr = new Array();
        var flag = true;
        $("#tbody_billingLadders").find("tr[name='insertBillingLadder_tr']").each(function(){
            var ladderStartnumberValue = $(this).children("td").children("input[name='ladderStartnumberValue']").val();
            var ladderEndnumberValue = $(this).children("td").children("input[name='ladderEndnumberValue']").val();
            var unitPriceValue = $(this).children("td").children("input[name='unitPriceValue']").val();
            //非空判断
            if (NullOrUndefined(ladderStartnumberValue)) {
                promptMsg("请输入开始计数！");
                flag = false;
                return false;
            }
            if (NullOrUndefined(ladderEndnumberValue)) {
                promptMsg("请输入结束计数！");
                flag = false;
                return false;
            }
            if (NullOrUndefined(unitPriceValue)) {
                promptMsg("请输入单价！");
                flag = false;
                return false;
            }
            if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(unitPriceValue)) {
                promptMsg("计费单价必须≥0 & <1000，可保留两位小数位！");
                flag = false;
                return false;
            }
            //最后插入的计费阶梯
            billingLadderObject = {};
            billingLadderObject.ladderStartnumber = ladderStartnumberValue;
            billingLadderObject.ladderEndnumber = ladderEndnumberValue;
            billingLadderObject.unitPrice = unitPriceValue;
            billingLaddersArr.push(billingLadderObject);
        });

        //调取后台，进行编辑入库
        if(flag){
            billingRuleService.editBillingRule({
                action: 'editBillingRule',
                billingRuleId: $scope.billingRuleObject.billingRuleId,
                ruleAbbrev: $scope.billingRuleObject.ruleAbbrev,
                ruleFullname : $scope.billingRuleObject.ruleFullname,
                ruleRate:$scope.billingRuleObject.ruleRate,
                remark : $scope.billingRuleObject.remark,
                billingLadderEntityVOList : billingLaddersArr
            }, function (data) {
                if (data.status == "SUCCESS") {
                    promptMsg(data.data.msg);
                    $("#editBillingRuleModal").modal("hide");    //关闭编辑界面
                    $scope.billingRuleId = data.data.billingRuleId;

                    $scope.init();    //刷新Tree
                    $scope.hideAllInsertTr();   //隐藏插入阶梯计费的表的全部tr

                    setTimeout(function () {
                        //ztree模拟onClick点击事件（传入节点id，不是页面元素id）
                        $scope.imitateZTreeOnClick($scope.billingRuleId);
                        $scope.findBillingRules();  //刷新计费规则信息，包括阶梯计数
                    }, 100);
                } else {
                    promptMsg(data.errorReason);
                }
            }, $scope.requestError());
        }
    }

    // 加载计费规则信息，包括阶梯计数
    $scope.findBillingRules = function(){
        $.fn.jqLoading({ height: 100, width: 240, text: "查询中，请稍等...." });
        billingRuleService.findBillingRules({
            action: 'findBillingRules',
            billingRuleId: $scope.billingRuleId
        }, function (data) {
            $.fn.jqLoading("destroy");
            if (data.status == 'SUCCESS'){
                $scope.billingRuleEntityVO = data.data.billingRuleEntityVO;
                $scope.billingLadderEntityVOList = $scope.billingRuleEntityVO.billingLadderEntityVOList;
                //显示DIV
                $("#div_billingrule_table").show();
            } else {
                promptMsg(data.data.msg);
            }
        }, $scope.requestError());
    }

    //显示插入阶梯计费的表tr
    $scope.showInsertTr = function(){
        var $tr = $('<tr name="insertBillingLadder_tr">' +
            '<td class="efbTable-border" style="width: 100px;">' +
            '<input type="checkbox" name="chk_billingLadders" />' +
            '</td>' +
            '<td class="efbTable-border" style="width: 150px;">' +
            '<input type="text" name="ladderStartnumberValue" onfocus="hilite(this);" onblur="delite(this);" maxlength="5" style="width:70%;" oninput="this.value=this.value.replace(/[^0-9]/g,\'\')" />' +
            '</td>' +
            '<td class="efbTable-border" style="width: 150px;">' +
            '<input type="text" name="ladderEndnumberValue" onfocus="hilite(this);" onblur="delite(this);" maxlength="5" style="width:70%;" oninput="this.value=this.value.replace(/[^0-9]/g,\'\')" />' +
            '</td>' +
            '<td class="efbTable-border">' +
            '<input type="text" name="unitPriceValue" onfocus="hilite(this);" onblur="delite(this);" maxlength="6" style="width:70%;" oninput="this.value=this.value.replace(/[^0-9\.]/g,\'\')"/>' +
            '</td>' +
            '</tr>');
        $("#tbody_billingLadders").append($tr);
    };

    //关闭编辑计费规则窗口
    $scope.closeBillingRuleModal = function(){
        //取消页面输入，重新加载计费规则信息，包括阶梯计数（新增不需要）
        if(!NullOrUndefined($scope.billingRuleObject.billingRuleId)){
            $scope.findBillingRules();
        }
        //隐藏插入阶梯计费的表的全部tr
        $scope.hideAllInsertTr();
        $("#editBillingRuleModal").modal("hide");
    };

    //隐藏插入阶梯计费的表的全部tr
    $scope.hideAllInsertTr = function () {
        $("tr[name='insertBillingLadder_tr']").remove();
    };

    //删除计费阶梯，直接删除tr
    $scope.deleteBillingLadder = function () {
        //未选择计费阶梯直接点击删除，应提示“没有选中计费阶梯！”
        if(NullOrUndefined($('input[name="chk_billingLadders"]:checked').val())){
            promptMsg("没有选中计费阶梯！")
            return false;
        }
        $('input[name="chk_billingLadders"]:checked').each(function (i) {
            $(this).parent().parent().remove();
        });
    };

    //删除计费规则
    $scope.deleteBillingRule = function () {
        if($scope.billingRuleEntityVO == null){
            promptMsg("请选择待删除的计费规则！");
            return;
        }

        //先查当前规则是否被合同用户引用，如果引用，则提示“当前规则被**合同用户引用，请删除引用后再行删除！”
        //如果当前规则没有被引用则提示“是否删除？”，确定后删除成功。
        billingRuleService.isBindContractUser({
            action : 'isBindContractUser',
            billingRuleId :  $scope.billingRuleEntityVO.billingRuleId
        }, function (data) {
            if (data.status == "SUCCESS") {
                if(NullOrUndefined(data.data.msg)){
                    //没有被引用，删除！
                    function confirmSubmit() {
                        billingRuleService.deleteBillingRule({
                            action : 'deleteBillingRule',
                            billingRuleId :  $scope.billingRuleEntityVO.billingRuleId
                        }, function (data1) {
                            if (data1.status == "SUCCESS") {
                                promptMsg(data1.data.msg);
                            } else {
                                promptMsg(data1.errorReason);
                            }
                            //重新加载计费规则Tree
                            $scope.init();
                            $scope.billingRuleEntityVO = null;
                        }, $scope.requestError());
                    }
                    confirmMsg("确定删除这个计费规则吗？", confirmSubmit, null);
                }else {
                    promptMsg("当前规则被" + data.data.msg + "合同用户引用，请删除引用后再行删除！");
                }
            } else {
                promptMsg(data.errorReason);
            }
        }, $scope.requestError());
    };

    //----------------------文件夹树结构---------------------------------------------
    var setting = {
        view: {
            showIcon: false    //不显示图标
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: zTreeOnClick
        }
    };

    //ztree模拟onClick点击事件（传入节点id，不是页面元素id）
    $scope.imitateZTreeOnClick = function (nodeId) {
        var tObj = $.fn.zTree.getZTreeObj("billingRuleTree");
        // 根据树id来获取节点，这里treeId是树对象里节点id，不是页面元素id
        var selectedNode = tObj.getNodeByParam("id", nodeId);
        // 根据节点，默认选中节点
        tObj.selectNode(selectedNode);
    };

    //获取计费规则Tree
    $scope.getTreeForBillingRule = function () {
        billingRuleService.getBillingRuleTree({
            action: 'getBillingRuleTree'
        }, function (data) {
            var treeObj = $.fn.zTree.init($("#billingRuleTree"), setting, data);
        }, $scope.requestError());
    };

    //计费规则树状图单击事件
    function zTreeOnClick(event, treeId, treeNode) {
        //树状节点层级
        $scope.treeLevel = treeNode.level;
        if($scope.treeLevel == 0){   //不处理根节点的单击事件
            $scope.billingRuleEntityVO = null;
            $scope.billingLadderEntityVOList = null;
            //显示DIV
            $("#div_billingrule_table").hide();
        }else {
            $scope.billingRuleId = treeNode.id;
            //加载计费规则信息，包括阶梯计数
            $scope.findBillingRules();
        }
    }

    //编辑计费规则
    $scope.toEditBillingRule = function (operate) {
        if(operate == "2"){
            if($scope.billingRuleEntityVO == null || $scope.treeLevel == 0){
                $scope.billingRuleEntityVO = null;
                promptMsg("请选择待编辑的计费规则！");
                return;
            }
            $scope.billingRuleObject = $scope.billingRuleEntityVO;
        }else{
            $scope.billingRuleObject = {ruleRate:20};
        }
        //模态框居中： 将事件监听的事件改成show.bs.modal 即可解决
        $('#editBillingRuleModal').on('show.bs.modal', centerModals("editBillingRuleModal"));
        $("#editBillingRuleModal").modal({
            backdrop: "static",//点击空白处不关闭对话框
            keyboard:false // 按esc键盘不关闭
        });
    }
});